 var xmlDoc;
	  var store;
var mainPanel,viewMap,bar ; 
var btnL,btnR;
var currentHour ;
var id_day;
var index = 0;
var title1 = 'set your position';
var title2 = 'select a bus station';
var title3 = 'select a bus line';

var title4= 'next busses:';

var xmlhttp;
var markerYourPos;
var stations=[];
var busses=[];
var selectedBusses=[];

var selectedBussesName=[];
var markBubble;
var markers=[];
var hours_busses=[];
var station_id;
var hoursInterval;
var tst=0;
var bussesPanel;
var brk = false;

function station(id,lat,long,name,dir,busses){
	 this.id= id;
	 this.latitude= lat;
	 this.longitude = long;
	 this.name = name;		
	 this.direction = dir;
	 this.busses = busses;
	  
 }  


 function bus(id,bus_name  ){
	 this.id= id;
	 this.name= bus_name; 
 } 

 
 
 function hours_bus(hours,bus){
	  this.hours= hours;
		 this.bus= bus;
 }

	function convertHours(){
		 
		 if(xmlhttph.readyState == 4)
	       {
	        xmlDoc=xmlhttph.responseXML; 
		    var root = xmlDoc.getElementsByTagName("xml");
		    var hs=[];
		    var bs_name=0 ;
		   for(var i=0; i<root[0].childNodes.length;i++){
			    //Create a new row for tbody
			 //  Ext.Msg.Alert('xml',root[0]);
			   var item= root[0].childNodes[i]  ;
			   var h = item.childNodes[0].childNodes[0].data;
			   bs_name =  item.childNodes[1].childNodes[0].data ;
			  
			 hs.push(h);
		    } 
		   var tmp = new hours_bus(hs,bs_name);
		   hours_busses.push(tmp);
	       }
	}
	function getHours(){
		brk = false;
		//.............statie - station_id
		//................ busses id = selectedBusses[]
		//.....................hour =    currentHour
		  calcCurrentTime();
		//................day = id_day
		  hours_busses=[];
		  tst=100;
		  for (var i=0 ; i < selectedBusses.length; i++) {
			  xmlhttph=new XMLHttpRequest(); 
			  xmlhttph.open("GET","php/getHours.php?hour="+currentHour+"&id_bus="+selectedBusses[i]+"&id_station="+station_id+"&id_day="+id_day,false);
			  xmlhttph.send();
			  convertHours(xmlhttph);
		   
		  }
		  
		   
	}
function calcCurrentTime(){
	var dt= new Date();
	currentHour = "";
	currentHour= dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
	
	 
	if(dt.getDay()<6)id_day=1;
	else if(dt.getDay()==6)id_day=2;
	else id_day=3;
}




function putHour(name, hour){
	if(name!=""&&hour!=""){
	  var tmp;
	  if(busPassed(hour)==true){ 
		   if(getSecRemaining(toDate(hour))>600000) {
			   brk = true;
			   hoursInterval = clearInterval ( hoursInterval );
			   return false;
		   }
	  tmp =  {
	           xtype: 'container',
	           items: [{
	           html: "<div id='red' class='hour_row'> " +
	           		    "<div  class='bus'> "  +name+"</div >" +
	           	       " <div  class='hour'>"+getIntervalRemaining(hour)+"</div>" +
	           	     "</div>"
	        }]};
	
	  }
	  else{
		tmp =  {
		           xtype: 'container',
		           items: [{
		        	html: "<div id='green' class='hour_row'> " +
	           		         "<div  class='bus'> "  +name+"</div >" +
		           	        " <div  class='hour'>"+getIntervalRemaining(hour)+"</div>" +
		           	     "</div>"
		        }]};
	}
		tst="putHours"; 
   bussesPanel.add(tmp);
	bussesPanel.doLayout();	
		
		
	}
} 
function putHours(){
	 bussesPanel.removeAll();
	for(var i=0; i<hours_busses.length;i++){
		for(var j=0;j<hours_busses[i].hours.length;j++){
			putHour(hours_busses[i].bus,hours_busses[i].hours[j]);
			if(brk==true) break;
		}
		if(brk==true) break;
	}
	//putHour("10","10:05:00");
//	if(brk==true) {
//		dis=setInterval ( 'dispatcher()', 1000 );
//		brk=false;
//	}
}
var dis;
function dispatcher(){
	 
	putHours();
	hoursInterval = setInterval ( 'putHours()', 1000 );
	 dis = clearInterval ( dis );
}


function busPassed(str){
	var date = new Date();
    var time = toDate(str);
	var ret = time.getTime()-date.getTime();
	if( ret<0) return true;
}
function toDate(dStr ) {
	var now = new Date(); 
 		now.setHours(dStr.substr(0,dStr.indexOf(":")));
 		now.setMinutes(dStr.substr(dStr.indexOf(":")+1, dStr.indexOf(":")));
 		now.setSeconds(dStr.substr(dStr.indexOf(":")+4));
 		return now;
	 
}
function getSecRemaining(time){
	var date = new Date();
	var ret = time.getTime()-date.getTime();
	return Math.abs( ret  );
}
function getMin(m){
	if(m<10)
		 return  "0"+m;
		return m;
}

function getSec(s){
	if(s<10)
	 return  "0"+s;
	return s;
}

function getIntervalRemaining(dStr){
	var time = toDate(dStr);
	var nr_sec= getSecRemaining(time);
	var d = new Date(nr_sec);
	
	 var min = getMin(d.getMinutes());
	 var sec= getSec(d.getSeconds());
	
	return min+":"+sec;
}

Ext.setup({
	
	//bara aia de sus
	 statusBarStyle:  'black-translucent',
//  tabletStartupScreen: 'tablet_startup.png',
//  phoneStartupScreen: 'phone_startup.png',
//  icon: 'icon.png',
  glossOnIcon: false, 
  
  onReady: function(){
		//object
	  markBubble = new google.maps.InfoWindow();
 
	  
	  function clearSelectedBusses(){
		  	selectedBusses = [];
		  	selectedBussesName = [];
		  	busses = [];
		  	bussesPanel.removeAll();
	  }
	
	  function addStationsToMap(){
		  for(var i=0; i<stations.length ;i++){
			  addStation(stations[i]);
		  }
	  }
	 function convertStations(){

		   if(xmlhttp.readyState == 4)
	       {
			   xmlDoc=xmlhttp.responseXML; 
		   var root = xmlDoc.getElementsByTagName("xml");
		    
		   for(var i=0; i<root[0].childNodes.length;i++){
			    //Create a new row for tbody
			 //  Ext.Msg.Alert('xml',root[0]);
			   var item= root[0].childNodes[i]  ;
			   var st = new station(
					   item.childNodes[0].childNodes[0].data,
					   item.childNodes[1].childNodes[0].data,
					   item.childNodes[2].childNodes[0].data,
					   item.childNodes[3].childNodes[0].data,
					   item.childNodes[4].childNodes[0].data,
					   item.childNodes[5].childNodes[0].data
			   ); 
			 stations.push(st);
		   } 
	       }
	 } 
	 function getStations(long ,lat )
		{
		   xmlhttp=new XMLHttpRequest(); 
		   xmlhttp.open("GET","php/getStations.php?latitude="+lat+"&longitude="+long,false);
		   xmlhttp.send();
		   convertStations();
		   addStationsToMap();  
		 
		};
	
		
		
	function addBus(bus){ 
		 
		bussesPanel.add({
			xtype: 'togglefield',
			name: bus.id ,
	       label:"Bus nr. "+bus.name ,
	       listeners: { 
	           change: function (slider, thumb, newValue, oldValue) {
	               if (oldValue == 0 && newValue == 1) {
	            	   selectedBusses.push( slider.getName() );  
	            	   btnR.setVisible(true);
	            	   // Changing from off to on...do something?
	               }
	               else if (oldValue == 1 && newValue == 0){
	                   // Changing from on to off...do something?
	            	   var idx = selectedBusses.indexOf(slider.getName()); // Find the index
	            	  if(idx!=-1) selectedBusses.splice(idx, 1); 
	            	  if(selectedBusses.length==0)btnR.setVisible(false);
	               }
	           }
	       }
        }); 
	};
		
	 function addBussesToPanel(){
			  for(var i=0; i<busses.length ;i++){
				  addBus(busses[i]);
				  bussesPanel.setScrollable('vertical');
				  bussesPanel.doLayout();
			  }
			   
		  }
	 function convertBusses(){

			   if(xmlhttp.readyState == 4)
		       {
		        xmlDoc=xmlhttp.responseXML; 
			    var root = xmlDoc.getElementsByTagName("xml");
			    
			   for(var i=0; i<root[0].childNodes.length;i++){
				    //Create a new row for tbody
				 //  Ext.Msg.Alert('xml',root[0]);
				   var item= root[0].childNodes[i]  ;
				   var bs = new bus(
						   item.childNodes[0].childNodes[0].data,
						   item.childNodes[1].childNodes[0].data 
				   ); 
				 busses.push(bs);
			    } 
		       }
			   
			    
		 }
		function getBusses(id_station  )
		{
		   xmlhttp=new XMLHttpRequest(); 
		   xmlhttp.open("GET","php/getBusses.php?id_station="+id_station,false);
		   xmlhttp.send();
		   convertBusses(); 
		 tst= "getBusses";
		};
	 
	 function goLeft(){
			 
			index = index - 1;
			if(index==0){
				bar.setTitle(title1);
				btnL.setVisible(false); 
				btnR.setVisible(true); 
				clearBusStations(); 
			}
			if(index==1){
				bar.setTitle(title2);
				btnR.setVisible(true); 
				getStations(markerYourPos.position.lng(),markerYourPos.position.lat());
				
				mainPanel.setActiveItem(0);  
			}
			if(index==2){
				bussesPanel.removeAll();
				bar.setTitle(title3);
				btnR.setVisible(false);  
				hoursInterval = clearInterval ( hoursInterval );
				clearSelectedBusses();
				getBusses(station_id);
				 
				addBussesToPanel(); 
			}
	 };
	 function goRight(){
			 
				
				
				if(index==0){ 
					bar.setTitle(title2);
					btnR.setVisible(false); 
					btnL.setVisible(true);
				//var coords = viewMap.geo.coords;
				//populate();
					getStations(markerYourPos.position.lng(),markerYourPos.position.lat());
					 
     			}
				
				if(index==1){
					bar.setTitle(title3);
					btnR.setVisible(false);
					//clearBusStations();

					 clearSelectedBusses();
					mainPanel.setActiveItem(1);
					getBusses(station_id);
					 
					addBussesToPanel(); 
				}
				 
				if(index == 2){
					btnR.setVisible(false);
 
					bar.setTitle(title4);
					
					getHours(); 
					putHours();
					hoursInterval = setInterval ( 'putHours()', 1000 );

				}
				index = index + 1;
	};
	
	
	
	btnL = new Ext.Button({
				iconMask: true,
				centered: true,
				iconCls: 'arrow_left',
				ui: 'plain',
				style: 'margin:0;', 
				handler: goLeft
	});
	btnR = new Ext.Button({ 
			iconMask: true,
			centered: true,
			iconCls: 'arrow_right',
			ui: 'plain',
			style: 'margin:0;',		 
			handler: goRight
	} );
	viewMap =  new Ext.Map({
			title: 'Map',  
            useCurrentLocation: true,
			mapOptions: {
				zoom: 14
				} 			 
	}); 
	
	 
	bussesPanel =  new Ext.Panel({
		 
    }); 
	
	bar = new Ext.Toolbar({
			dock: 'top',
			title: title1,
			items:[btnL,{xtype:'spacer'},btnR]
	});
		  
	mainPanel = new Ext.Panel({
			 fullscreen: true, 
			 layout:'card',
	             	
			    cardSwitchAnimation: 'cube', 
			    items: [ viewMap, bussesPanel],
			    dockedItems:[ bar,
			                  {
			    				xtype: 'container',
			    				dock: 'top',
			    				items: [{html:"<p id='title'>Because Sibiu deserves it!  &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp AB &copy;</p>"}]
			                  }
			    ]
	});
		
    function addStation(station){ 
		//set marker on mapbearing2009
 		var latLng = new google.maps.LatLng(station.latitude,station.longitude);
        var marker = new google.maps.Marker({
			 map: viewMap.map,
			 position: latLng,
			 draggable: true, //tre sa fie draggable ca sa functioneze bubble>>>>???/ 
			 title:station.id,
			 icon:'images/icons/busStopIcon.png',
			 shadow: 'images/icons/shIcon.png'
		    });
        markers.push(marker);
		  
		  
		 google.maps.event.addListener(marker, "click",function(){
			  var content= "<div>"+station.name+"</br>"+station.direction+"</div>";
			  station_id= marker.getTitle();
			  markBubble.setContent(   content);
		      markBubble.open(viewMap.map,marker);
		      btnR.setVisible(true); 
		  });
	};
	
	function clearBusStations(){
		 for (var i= markers.length; i >0 ; i--) {
			 markers.pop().setMap(null); // remove markers from map 
			};
			 markers = []; 
			 stations= [];
		 
	 };

    function addMarker(){
			var coords = viewMap.geo.coords;
			//set marker on mapbearing2009
	 		var latLng = new google.maps.LatLng(coords.latitude,coords.longitude);
	 		markerYourPos = new google.maps.Marker({
				 map: viewMap.map,
				 position: latLng,
				 draggable: true, 
				 icon:'images/icons/hereIcon.png',
				 shadow: 'images/icons/shIcon.png'
			    });
			  
			  
			 google.maps.event.addListener(markerYourPos, "click",function(){
			 	 markBubble.setContent("your position ");
			     markBubble.open(viewMap.map,markerYourPos);
			   });
		};
		function	refresh() {
	 		 addMarker();
	 		btnL.setVisible(false);	
			 };
		
		// mainPanel.getTabBar().doLayout();
	     viewMap.geo.on('update', refresh);
 
	   
	
	}
});